package com.future.mayi.widget;

import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.future.mayi.activity.BasePage;
import com.future.baselib.utils.CommonUtils;
import com.future.mayi.R;
import com.future.mayi.adapter.BasePageAdapter;
import com.future.mayi.app.App;
import com.future.mayi.fragment.ImagePage;
import com.future.mayi.model.BannerModel;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by 周大虎 on 2017/3/4.
 */

public class CarouselTitleView extends LinearLayout implements View.OnClickListener {

    private boolean isCarousel = false;

    private ViewPager vpIndex;

    private LinearLayout llDot;

    private List<ImageView> ivDots;

    private long carouseTime = 3000;

    private int inPage = 0;

    private int pageSize = 0;

    private Context mContext;

    private boolean isDefault = true;

    private boolean isAnim = true;
    private boolean goneDot = false;

    int dotHeight = 2;
    int dotWidth = 27;

    private Handler mHandler = new Handler();

    public CarouselTitleView(Context context) {
        super(context);
        init(context);
    }

    public CarouselTitleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CarouselTitleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    public interface OnItemPageClick {
        void onItemPage(int position);
    }


    private OnItemPageClick onItemPageClick;


    private void init(Context context) {
        mContext = context;
        View.inflate(context, R.layout.view_title_carousel, this);
        vpIndex = findViewById(R.id.vp_index);
        llDot = findViewById(R.id.ll_index_page_item);
        setGoneDot(goneDot);

        dotHeight = CommonUtils.dip2px(mContext, dotHeight);
        dotWidth = CommonUtils.dip2px(mContext, dotWidth);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) vpIndex.getLayoutParams();
        layoutParams.width = CommonUtils.getScreenSize(mContext)[0];
        layoutParams.height = (int) (((float) layoutParams.width - CommonUtils.dip2px(mContext, 12.0f * 2.0f)) * (175.0f / 351.0f));
    }

    private List<String> list;


    public void setOnItemPageClick(OnItemPageClick onItemPageClick) {
        this.onItemPageClick = onItemPageClick;
    }

    public void setBannerModel(List<BannerModel> list) {
        List<String> imgList = new ArrayList<>(4);
        if (list == null || list.size() == 0) {
            imgList.add("");
            setData(imgList);
            return;
        }
        for (BannerModel bannerModel : list) {
            imgList.add(bannerModel == null ? "" : bannerModel.getAdvert_img());
        }
        setData(imgList);
    }

    public void setData(List<String> list) {

        if (this.list != null && App.getGson().toJson(list).equals(App.getGson().toJson(this.list)))
            return;


        this.list = list;

        if (ivDots != null)
            ivDots.clear();


        ivDots = new ArrayList<>();
        llDot.removeAllViews();
        List<BasePage> indexCarouselPageList = new ArrayList<>(10);

        ImagePage carouselPage;
        if (list == null) {
            pageSize = 0;
            carouselPage = new ImagePage(mContext);
            carouselPage.setData(null);
            indexCarouselPageList.add(carouselPage);
        } else {
            pageSize = list.size();
            for (int i = 0; i < pageSize; i++) {
                carouselPage = new ImagePage(mContext);
                carouselPage.setData(list.get(i));
                indexCarouselPageList.add(carouselPage);
                carouselPage.getView().setTag(i);
                carouselPage.getView().setOnClickListener(this);
            }
        }

        vpIndex.setAdapter(new BasePageAdapter(indexCarouselPageList, new ArrayList<String>()));

        int margin = CommonUtils.dip2px(mContext, 2);
        for (int i = 0; i < pageSize; i++) {
            ImageView dotView = new ImageView(mContext);
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//            params.leftMargin = margin;// 设置小圆点的外边距
//            params.rightMargin = margin;
            params.height = dotHeight;// 设置小圆点的大小
            params.width = dotWidth;
            params.gravity = Gravity.CENTER;
            dotView.setBackgroundColor(getResources().getColor(R.color.white));
            llDot.addView(dotView, params);
            ivDots.add(dotView);
        }

        vpIndex.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < ivDots.size(); i++) {
                    ivDots.get(i).setBackgroundColor(getResources().getColor(i == position ? R.color.white : R.color.white_40));
                }
                inPage = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        isCarousel = true;
        if (pageSize > 1 && isAnim) {
            mHandler.removeCallbacks(task);
            mHandler.postDelayed(task, carouseTime);
        }


    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isCarousel = false;
                break;
            case MotionEvent.ACTION_UP:
                isCarousel = true;
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    private final Runnable task = new Runnable() {
        @Override
        public void run() {
            Rect rect = new Rect();
            isCarousel = getGlobalVisibleRect(rect);
            if (isCarousel) {
                int position = 0;
                if (isDefault) {
                    if ((inPage + 1) == pageSize) {
                        position = inPage - 1;
                        isDefault = false;
                    } else {
                        position = inPage + 1;
                    }
                } else {
                    if (inPage == 0) {
                        position = 1;
                        isDefault = true;
                    } else {
                        position = inPage - 1;
                    }
                }
                vpIndex.setCurrentItem(position);

                mHandler.removeCallbacks(task);
                mHandler.postDelayed(task, carouseTime);
            } else {
                mHandler.removeCallbacks(task);
                mHandler.postDelayed(task, carouseTime);
            }
        }
    };


    @Override
    public void onClick(View v) {
        if (v.getTag() != null && v.getTag() instanceof Integer) {
            if (onItemPageClick != null)
                onItemPageClick.onItemPage((Integer) v.getTag());
        }
    }

    public void setAnim(boolean anim) {
        isAnim = anim;
    }


    public void setGoneDot(boolean goneDot) {
        this.goneDot = goneDot;
        if (llDot != null)
            llDot.setVisibility(goneDot ? GONE : VISIBLE);
    }

    public void setCarouseTime(long carouseTime) {
        this.carouseTime = carouseTime;
    }
}
